package com.chenzouquan.util.toJson;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.dataformat.xml.XmlMapper;
import org.w3c.dom.Document;
import org.xml.sax.SAXException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

public class XmlToJsonConverter {
    public static String convertXmlToJson(String xmlFilePath, String jsonFilePath) throws IOException {
        // 创建XmlMapper对象用于XML转换
        XmlMapper xmlMapper = new XmlMapper();

        // 创建ObjectMapper对象用于JSON转换
        ObjectMapper jsonMapper = new ObjectMapper();

        // 读取XML文件
        File xmlFile = new File(xmlFilePath);

        // 将XML文件转换为JsonNode对象
        JsonNode jsonNode = xmlMapper.readTree(xmlFile);

        // 将JsonNode对象转换为JSON字符串
        String jsonString = jsonMapper.writeValueAsString(jsonNode);

        // 将JSON字符串写入JSON文件
        File jsonFile = new File(jsonFilePath);
        jsonMapper.writeValue(jsonFile, jsonNode);

        // 删除原文件
        new File(xmlFilePath).delete();
        return jsonFilePath;
    }
}

